package com.rzico.sbl.ui.member

import android.widget.TextView
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.view.isVisible
import com.rzico.sbl.R
import com.rzico.sbl.databinding.ActivityCommonListBinding
import com.rzico.sbl.model.CouponData
import com.rzico.sbl.viewmodel.TicketViewModel
import com.xinnuo.common.extend.find
import com.xinnuo.common.extend.get
import com.xinnuo.common.extend.getExtra
import com.xinnuo.common.extend.visibleValue
import com.xinnuo.common.helper.getTimeString
import com.xinnuo.common.decoration.SpaceTBDecoration
import com.xinnuo.common.helper.intValue
import com.xinnuo.common_ui.base.BaseActivity
import com.xinnuo.common_ui.base.addItems
import com.xinnuo.common_ui.base.loadLinear
import com.xinnuo.common_ui.utils.bindLifeCycle
import com.xinnuo.common_ui.utils.showHintDialog
import com.xinnuo.common_ui.utils.subscribeByFinally
import com.xinnuo.common_ui.utils.subscribeBySuccess
import com.xinnuo.slimadapter.SlimAdapter

class MemberCouponActivity : BaseActivity(R.layout.activity_common_list) {

    private val mBinding by lazy { ActivityCommonListBinding.bind(getRootView()) }
    private lateinit var mTotalView: TextView

    override fun getViewModel() = get<TicketViewModel>()

    override fun initData() {
        initTitle(title = "优惠券")

        initLayout()

        mBinding
            .listLayout
            .swipeRefresh
            .isRefreshing = true

        getData()
    }

    private fun initLayout() {
        mBinding.listLayout.apply {
            emptyLayout.also {
                it.emptyHint.text = "暂无相关优惠券信息！"
            }

            recycleList.also { layout ->
                layout.loadLinear(
                    refresh = swipeRefresh,
                    onRefresh = { getData() }
                )

                layout.addItemDecoration(SpaceTBDecoration())

                mAdapter = SlimAdapter.creator()
                    .register<CouponData>(R.layout.item_coupon_list) { jector, bean, index ->
                        jector.apply {
                            gone(R.id.item_coupon_label)
                            inVisible(R.id.item_coupon_type)

                            text(R.id.item_coupon_name, bean.couponName)

                            with<TextView>(R.id.item_coupon_count) {
                                it.text = bean.amount.trimEnd('元', '折')
                                if (bean.type == "product") it.text = "1"
                            }

                            text(
                                R.id.item_coupon_title,
                                "${
                                    when (bean.scope) {
                                        "all" -> "全场"
                                        "shop" -> "店内"
                                        "mall" -> "商城"
                                        else -> ""
                                    }
                                }${
                                    when (bean.type) {
                                        "fullcut" -> "满减优惠券"
                                        "discount" -> "满折优惠券"
                                        "product" -> "商品券"
                                        else -> ""
                                    }
                                }"
                            )
                            text(
                                R.id.item_coupon_range,
                                "使用截止日期：${
                                    bean.expireDate?.let { it.getTimeString() } ?: "永久有效"
                                }"
                            )

                            visibility(
                                R.id.item_coupon_name,
                                visibleValue { bean.type == "product" }
                            )

                            visibility(
                                R.id.item_coupon_hint1,
                                visibleValue { bean.type == "fullcut" }
                            )

                            with<TextView>(R.id.item_coupon_hint2) {
                                it.isVisible = bean.type != "fullcut"
                                it.text = when (bean.type) {
                                    "product" -> "张"
                                    else -> "折"
                                }
                            }

                            with<ConstraintLayout>(R.id.item_coupon) {
                                when (bean.type) {
                                    "fullcut" -> it.setBackgroundResource(R.mipmap.icon_manager17)
                                    "discount" -> it.setBackgroundResource(R.mipmap.icon_manager18)
                                    "product" -> it.setBackgroundResource(R.mipmap.icon_manager19)
                                }
                            }

                            longClicked {
                                deleteCoupon(bean.id, index)
                                true
                            }
                        }
                    }
                    .attachTo(layout)
                    .addHeader(getIContext(), R.layout.header_member_coupon) { _, view ->
                        mTotalView = view.find(R.id.coupon_total)
                    }
            }
        }
    }

    /**
     * 删除优惠券
     */
    private fun deleteCoupon(couponId: String, index: Int) {
        showHintDialog(
            title = "优惠券",
            hint = "确定要删除该优惠券吗？",
            sure = "删除",
            onSure = {
                getViewModel()
                    .couponDel(couponId)
                    .bindLifeCycle(getLifecycleOwner())
                    .subscribeBySuccess(
                        event = getViewModel(),
                        onSuccess = {
                            showToast("优惠券删除成功！")

                            mList.removeAt(index - 1)
                            mAdapter.apply {
                                notifyItemRemoved(index)
                                notifyItemRangeChanged(index, itemCount - index)
                            }

                            totalCount()

                            mBinding.listLayout
                                .emptyLayout
                                .emptyView.isVisible = mList.isEmpty()
                        }
                    )
            }
        )
    }

    /**
     * 优惠券列表
     */
    override fun getData(index: Int, isLoading: Boolean) {
        getViewModel()
            .couponList(intent.getExtra("cardId"))
            .bindLifeCycle(getLifecycleOwner())
            .subscribeByFinally(
                event = getViewModel(),
                onSuccess = {
                    mList.apply {
                        clear()
                        addItems(it)
                    }

                    mAdapter.setDataList(mList)
                },
                onFinally = {
                    totalCount()

                    mBinding
                        .listLayout
                        .apply {
                            swipeRefresh.isRefreshing = false

                            emptyLayout
                                .emptyView
                                .isVisible = mList.isEmpty()
                        }
                }
            )
    }

    /**
     * 优惠券总张数
     */
    private fun totalCount() {
        var ticketCount = 0
        mList.forEach {
            it as CouponData
            ticketCount += it.stock.intValue
        }
        mTotalView.text = "优惠券总计：${ticketCount} 张"
    }

}